package cn.tedu.straw.portal.controller;


import cn.tedu.straw.portal.dto.PostAnswerDTO;
import cn.tedu.straw.portal.dto.StudentRegisterDTO;
import cn.tedu.straw.portal.ex.ParamValidationException;
import cn.tedu.straw.portal.security.LoginUserInfo;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.util.R;
import cn.tedu.straw.portal.vo.AnswerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-02-26xczxc
 */
@RestController
@RequestMapping("/portal/answer")
public class AnswerController {
    @Autowired
    IAnswerService answerService;
    @RequestMapping("/post")
    //http://localhost:8080/portal/answer/post?questionId=1&content=啊实打实大苏打
    public R<Void> post(@Valid PostAnswerDTO postAnswerDTO, BindingResult bindingResult,
                        @AuthenticationPrincipal LoginUserInfo loginUserInfo){
        if(bindingResult.hasErrors()){
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            throw new ParamValidationException(errorMessage);
        }
        Integer userId = loginUserInfo.getId();
        String userNickName = loginUserInfo.getNickName();
        answerService.post(postAnswerDTO,userId,userNickName);
        return R.ok();
    }
    @GetMapping("")
    public R<List<AnswerVO>> getAnswerList(Integer questionId){
        if(questionId == null || questionId<1){
            throw new ParamValidationException("获取答案列表失败!缺少必要的参数");
        }
        return R.ok(answerService.getAnswerList(questionId));
    }
}
